﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using FineUI;
using Newtonsoft.Json.Linq;
using ZHDJ.Core.Log;
using ZHDJ.Data;
using Menu = ZHDJ.Data.Models.Box.Menu;

namespace AppBox.BLL
{
    public class MainPage: PageBase
    {
         

       
        /// <summary>
        /// 1后台管理 2 组织中心 3个人中心 4;注册用户
        /// </summary>
        public virtual int PageFlag { get;  }


        /// <summary>
        /// 帮助
        /// </summary>
        /// <param name="button"></param>
        public void ToolHelp(Button button)
        {
            JArray ja = JArray.Parse(ConfigHelper.HelpList);
            foreach (JObject jo in ja)
            {
                MenuButton menuItem = new MenuButton();
                menuItem.EnablePostBack = false;
                menuItem.Text = jo.Value<string>("Text");
                menuItem.Icon = IconHelper.String2Icon(jo.Value<string>("Icon"), true);
                menuItem.OnClientClick = String.Format("addExampleTab('{0}','{1}','{2}')", jo.Value<string>("ID"), ResolveUrl(jo.Value<string>("URL")), jo.Value<string>("Text"));

                button.Menu.Items.Add(menuItem);
            }
        }

        /// <summary>
        /// 注册脚本
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="menus"></param>
        /// <param name="regionLeft"></param>
        public void RegisterMainJs(JObject ids, List<Menu> menus,Region regionLeft)
        {
            // 注册客户端脚本，服务器端控件ID和客户端ID的映射关系
            
            ids.Add("userName", GetIdentityName());
            ids.Add("userIP", Request.UserHostAddress);
            ids.Add("onlineUserCount", GetOnlineCount());

            if (ConfigHelper.MenuType == "accordion" && PageFlag==1)
            {
                Accordion accordionMenu = InitAccordionMenu(menus, regionLeft);
                ids.Add("treeMenu", accordionMenu.ClientID);
                ids.Add("menuType", "accordion");
            }
            else
            {
                Tree treeMenu = InitTreeMenu(menus, regionLeft);
                ids.Add("treeMenu", treeMenu.ClientID);
                ids.Add("menuType", "menu");
            }

            string idsScriptStr = String.Format("window.DATA={0};", ids.ToString(Newtonsoft.Json.Formatting.None));
            PageContext.RegisterStartupScript(idsScriptStr);
        }

        #region 获取用户可用的菜单列表

        // 获取用户可用的菜单列表
        public virtual List<Menu> ResolveUserMenuList()
        {
            // 当前登陆用户的权限列表
            List<string> rolePowerNames = GetRolePowerNames();
            // 当前用户所属角色可用的菜单列表
            List<Menu> menus = new List<Menu>();
            foreach (Menu menu in MenuHelper.Menus)
            {
                // 如果此菜单不属于任何模块，或者此用户所属角色拥有对此模块的权限
                if (menu.ViewPower == null || rolePowerNames.Contains(menu.ViewPower.Name))
                {
                    menus.Add(menu);
                }
            }
            return menus;
        }
        #endregion

        #region 创建手风琴菜单

        /// <summary>
        /// 创建手风琴菜单
        /// </summary>
        /// <param name="menus"></param>
        /// <returns></returns>
        private Accordion InitAccordionMenu(List<Menu> menus, Region regionLeft)
        {
            Accordion accordionMenu = new Accordion();
            accordionMenu.ID = "accordionMenu";
            accordionMenu.EnableFill = true;
            accordionMenu.ShowBorder = false;
            accordionMenu.ShowHeader = false;
            regionLeft.Items.Add(accordionMenu);


            foreach (var menu in menus.Where(m => m.Parent == null))
            {
                AccordionPane accordionPane = new AccordionPane();
                accordionPane.Title = menu.Name;
                accordionPane.Layout = Layout.Fit;
                accordionPane.ShowBorder = false;
                accordionPane.BodyPadding = "2px 0 0 0";
                accordionMenu.Items.Add(accordionPane);

                Tree innerTree = new Tree();
                innerTree.EnableArrows = true;
                innerTree.ShowBorder = false;
                innerTree.ShowHeader = false;
                innerTree.EnableIcons = true;
                innerTree.AutoScroll = true;
                accordionPane.Items.Add(innerTree);


                // 生成树
                ResolveMenuTree(menus, menu, innerTree.Nodes);

            }

            return accordionMenu;
        }

        #endregion

        #region 创建树菜单

        /// <summary>
        /// 创建树菜单
        /// </summary>
        /// <param name="menus"></param>
        /// <returns></returns>
        private Tree InitTreeMenu(List<Menu> menus, Region regionLeft)
        {
            Tree treeMenu = new Tree();
            treeMenu.ID = "treeMenu";
            treeMenu.EnableArrows = true;
            treeMenu.ShowBorder = false;
            treeMenu.ShowHeader = false;
            treeMenu.EnableIcons = true;
            treeMenu.AutoScroll = true;
            regionLeft.Items.Add(treeMenu);

            if ( PageFlag == 1)
                // 生成树
                ResolveMenuTree(menus, null, treeMenu.Nodes);
            else
            {
                ResolveMenuTree(menus, menus.FirstOrDefault(a=>a.Parent==null), treeMenu.Nodes);
            }

            if (treeMenu.Nodes.Count > 0)
            {
                // 展开第一个树节点
                treeMenu.Nodes[0].Expanded = true;
            }

            return treeMenu;
        }

        /// <summary>
        /// 生成菜单树
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="parentMenuId"></param>
        /// <param name="nodes"></param>
        private int ResolveMenuTree(List<Menu> menus, Menu parentMenu, FineUI.TreeNodeCollection nodes)
        {
            int count = 0;
            foreach (var menu in menus.Where(m => m.Parent == parentMenu))
            {
                FineUI.TreeNode node = new FineUI.TreeNode();
                nodes.Add(node);
                count++;

                node.Text = menu.Name;
                node.IconUrl = menu.ImageUrl;
                if (!String.IsNullOrEmpty(menu.NavigateUrl))
                {
                    var url = menu.NavigateUrl;
                    if (menu.NavigateUrl.ToLower().IndexOf("?") > 0 && PageFlag==2 )
                    {
                        url = menu.NavigateUrl + "&BranchID=" + BranchID;
                    }else if ( PageFlag == 2)
                    {
                        url = menu.NavigateUrl + "?BranchID=" + BranchID;
                    }

                    node.NavigateUrl = ResolveUrl(url);
                    //node.OnClientClick = String.Format("addTab('{0}','{1}','{2}')", node.NodeID, ResolveUrl(menu.NavigateUrl), node.Text.Replace("'", ""));
                }

                if (menu.IsTreeLeaf)
                {
                    node.Leaf = true;

                    // 如果是叶子节点，但是不是超链接，则是空目录，删除
                    if (String.IsNullOrEmpty(menu.NavigateUrl))
                    {
                        nodes.Remove(node);
                        count--;
                    }
                }
                else
                {
                    //node.SingleClickExpand = true;

                    int childCount = ResolveMenuTree(menus, menu, node.Nodes);

                    // 如果是目录，但是计算的子节点数为0，可能目录里面的都是空目录，则要删除此父目录
                    if (childCount == 0 && String.IsNullOrEmpty(menu.NavigateUrl))
                    {
                        nodes.Remove(node);
                        count--;
                    }
                }
            }
            return count;
        }

        #endregion

        /// <summary>
        /// 退出
        /// </summary>
        public void Exit()
        {
            try
            {
                var userLog = DB.PartyUserLoginLogs.FirstOrDefault(a => a.ID ==UserLogID);
                if (userLog != null)
                {
                    userLog.LastOpTime = DateTime.Now;
                    userLog.LoginOutTime = userLog.LastOpTime;
                    DB.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log4netHelper.WriteLog("用户退出", ex);
            }
            FormsAuthentication.SignOut();
            Session.Abandon();
            RedirectTo("default", "~/default.aspx");
        }

        public void LoadChangeRole(Button btnChangeRole, ToolbarSeparator toolbarSeparator)
        {
            var dt = PartyOrg.GetBranchManageByLoginId(CurrentUser.LoginID);
            if (dt.Rows.Count < 1)
            {
                btnChangeRole.Hidden = true;
                toolbarSeparator.Hidden = true;
                return;
            }
            btnChangeRole.Hidden = false;
            toolbarSeparator.Hidden = false;
            foreach (DataRow dr in dt.Rows)
            {
                MenuButton menuItem = new MenuButton();
                menuItem.EnablePostBack = false;
                menuItem.Text = Convert.ToString(dr["BranchName"]);
                menuItem.Icon = IconHelper.String2Icon("DoorIn", true);
                menuItem.OnClientClick = String.Format("changeRole('{0}');return false;", Convert.ToString(dr["BranchID"]));

                btnChangeRole.Menu.Items.Add(menuItem);
            }
        }
    }
}
